Often we will want to insert/inject variables into string eg. my_name = "Russ"

print("Hi " + my_name)

String Interpolation refers to formatting strings in various ways to permit injection.

Explorations of the .format() method/function and the f-strings (formatted string literals) newer in Python3.6.x plus


In [27]:
print('This is a String {}'.format('INSERTED'))


This is a String INSERTED

In [28]:
print('This is an example of MultiIndex insertions {} {} {}'.format('INSERTION1', 'INSERTION2', 'INSERTION3'))


This is an example of MultiIndex insertions INSERTION1 INSERTION2 INSERTION3

In [29]:
a = 'I1'
b = 'I2'
c = 'I3'

In [30]:
print('This is me jumping the gun and testing a theory {} {} {}'.format(a, b, c))


This is me jumping the gun and testing a theory I1 I2 I3

In [31]:
print('Now testing MultiIndexed Insertions without jumping the gun:' + 'The {2} {1} {0}'.format('fox', 'brown', 'quick'))


Now testing MultiIndexed Insertions without jumping the gun:The quick brown fox

Can also repeat an index eg. {0} {0} {0} - and use K2VP as below - cannot use numerical values (expressions and maloc rules).


In [32]:
print('The {q} {g} {f}'.format(f='fox', q='quick', g='golden'))


The quick golden fox

Repeat can also be used with keys: {f} {f} {f}

Float formatting follows "{value:width.precision f}"


In [33]:
result = 12987/8921

In [34]:
result


Out[34]:
1.4557785001681425

In [35]:
print('The result was {}'.format(result))


The result was 1.4557785001681425

In [36]:
print('The result was {r:1.6f}'.format(r=result))


The result was 1.455779

Formatted String literals AKA 'FString'.


In [37]:
name = 'Rusha'

In [39]:
print(f'Hi, he said his name was {name} because he drinks too much caffeine and rushes around.')


Hi, he said his name was Rusha because he drinks too much caffeine and rushes around.

In [44]:
age = 3000
real_name = 'Russell'
hobbits = 'AI, Art and Coding among others.'

In [45]:
print(f'HI, he said his name was {name} because he drinks a lot of caffeine and rushes about. I later found out after getting to know him, his real name is {real_name} and he is {age} years old and has a keen interest in {hobbits}')


HI, he said his name was Rusha because he drinks a lot of caffeine and rushes about. I later found out after getting to know him, his real name is Russell and he is 3000 years old and has a keen interest in AI, Art and Coding among others.

In [53]:
pi = u"\U0001D70B"

In [54]:
print(f'He also said he likes the idea of {pi}.')


He also said he likes the idea of 𝜋.

In [ ]: